package com.leyou.auth.service.impl;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.constants.redisConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.service.userAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.commons.exception.LyException;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Service
public class userAuthServiceImpl implements userAuthService {
    @Autowired
    private UserClient userClient;
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 用户登录验证
     * @param username
     * @param password
     * @param response
     */
    @Override
    public void login(String username, String password, HttpServletResponse response) {
        try {
            //调用服务通过用户名和密码查找用户
            UserDTO userDTO = userClient.queryUserByUserNameAndPassword(username, password);
            if(null==userDTO){
                throw new LyException(400,"用户名或密码错误");
            }
            //把userDTO转换成userdetail
            UserDetail userDetail = UserDetail.of(userDTO.getId(), userDTO.getUsername());
            //生成tocken
            String jwt = jwtUtils.createJwt(userDetail);
            //把jwt写入cookie
            writeCookie(response,jwt,-1);
        } catch (FeignException e) {
           throw new LyException(e.status(),e.getMessage());
        }
    }

    @Override
    public void logout(String jwt, HttpServletResponse response) {
        // 校验cookie中的token的有效性
        Payload payload = null;
        try {
            payload = jwtUtils.parseJwt(jwt);
        } catch (Exception e) {
            // 如果无效，什么都不做
            return;
        }
        // 如果有效，删除cookie（重新写一个cookie，maxAge为0）
        writeCookie(response,jwt,0);
        //删除redis里的数据
        redisTemplate.delete(redisConstants.JTI_KEY_PREFIX+payload.getUserDetail().getId());
    }

    private void writeCookie(HttpServletResponse response, String tocken,Integer maxAge) {
        Cookie cookie = new Cookie(JwtConstants.COOKIE_NAME,tocken);
        // 是否禁止JS操作cookie，避免XSS攻击
        cookie.setHttpOnly(true);
        //cookie的作用域
        cookie.setDomain(JwtConstants.DOMAIN);
        //cookie的请求路径,代表一切路径
        cookie.setPath("/");
        //设置有效时间,浏览器关闭则失效
        cookie.setMaxAge(maxAge);
        //存入客户端浏览器
        response.addCookie(cookie);
    }
}
